package com.zzyl.member.utils;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.framework.interceptor.impl.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class smallProgramInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1 获取请求头中的token(authorization)
        String token = request.getHeader("authorization");
        log.warn("拦截器开始工作");
        //2判断token是否为空，如果为空响应401
        if (ObjectUtil.isEmpty(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.warn("token不能为空");
            throw new BaseException("token不能为空");
        }

        //3解析token 如果解析失败响应401
        Claims claims = tokenService.parseToken(token);
        if (ObjectUtil.isEmpty(claims)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.warn("token解析失败");
            throw new BaseException("token解析失败");
        }

        //4解析token中的id 如果为空响应401
        Long id = MapUtil.get(claims, "id", Long.class);
        if (ObjectUtil.isEmpty(id)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.warn("id不能为空");
            throw new BaseException("id不能为空");
        }
        log.warn("将本次登录人的ID存到了ThreadLocal当中");
        UserThreadLocal.set(id);
        return true;


    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
